package sg.com.techstudio.tafep.dao;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import sg.com.techstudio.tafep.obj.CompanyObj;
import sg.com.techstudio.tafep.obj.RegisterObj;

@Repository("companyDao")
@Transactional
public class CompanyDao {
	private static final Log log = LogFactory.getLog(CompanyDao.class);
	
	@Autowired
	private SessionFactory sessionFactory;
	
	public List<CompanyObj> getCompanyList(){
		return getCompanyList(null);
	}
	
	@SuppressWarnings("unchecked")
	public List<CompanyObj> getCompanyList(String q){
		log.debug("getCompanyList() entry");
		Criteria c = sessionFactory.getCurrentSession().createCriteria(CompanyObj.class);
		if(!StringUtils.isBlank(q))
			c.add(Restrictions.ilike("name", q+"%"));
		c.addOrder(Order.asc("name"));
		return c.list();
	}
	
	public boolean validCompany(String companyName) {
		log.debug("validCompany() entry");
		Criteria c = sessionFactory.getCurrentSession().createCriteria(CompanyObj.class);
		c.add(Restrictions.eq("name", companyName));
		c.setProjection(Projections.rowCount());
		return (Long)c.uniqueResult() >0;
	}
	
	public CompanyObj getCompany(String companyName) {
		log.debug("validCompany() entry");
		Criteria c = sessionFactory.getCurrentSession().createCriteria(CompanyObj.class);
		c.add(Restrictions.eq("name", companyName));
		c.setMaxResults(1);
		return (CompanyObj)c.uniqueResult();
	}
	
	public void copyCompanyInfo(RegisterObj r) {
		log.debug("copyCompanyInfo() entry");
		if(StringUtils.isBlank(r.getCompanyName())) {
			r.setCompanyAddress("");//clear address
			return;
		}
		CompanyObj c = getCompany(r.getCompanyName());
		if(c==null)
			return;
		r.setCompanyAddress(c.getAddress());
	}
}
